package cn.iot.controller.data;

import cn.iot.common.api.CommonResult;
import cn.iot.common.utils.SysUserUtils;
import cn.iot.data.mapper.TStudentInfoMapper;
import cn.iot.data.mapper.TSysClassMapper;
import cn.iot.data.pojo.TStudentInfo;
import cn.iot.data.pojo.TSysClass;
import cn.iot.data.pojo.TSysDictDetail;
import cn.iot.data.service.impl.TStudentInfoServiceImpl;
import cn.iot.data.service.impl.TSysClassServiceImpl;
import cn.iot.data.service.impl.TSysDictDetailServiceImpl;
import cn.iot.sys.entity.SysRole;
import cn.iot.sys.entity.SysUser;
import cn.iot.sys.entity.SysUserRole;
import cn.iot.sys.service.impl.SysRoleServiceImpl;
import cn.iot.sys.service.impl.SysUserRoleServiceImpl;
import cn.iot.sys.service.impl.SysUserServiceImpl;
import cn.iot.utils.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
@RequestMapping("/data/class")
@Api(tags = "data-class => 基础数据班级信息维护")
public class ClassController {
    @Resource
    TStudentInfoServiceImpl studentInfoService;
    @Resource
    TStudentInfoMapper studentInfoMapper;
    @Resource
    TSysClassMapper classMapper;
    @Resource
    TSysClassServiceImpl classService;

    @ApiOperation("list => 获取菜单列表")
    @GetMapping("/list")
    @PreAuthorize("@ss.hasPermi('data:class:info')")
    public Object list(@RequestParam(required = false) String className,
                       @RequestParam(required = false) String status,
                       @RequestParam(required = false) String profession,
                       @RequestParam(required = false,defaultValue = "1") Integer pageNo,
                       @RequestParam(required = false,defaultValue = "1") Integer pageSize) {
        if (pageNo==null) {
            pageNo=1;
        }
        if (pageSize==null) {
            pageSize=1;
        }
        Page page = new Page();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        page.setTotalCount(classMapper.getlistCount(className,status,profession));
        List<TSysClass> list = classMapper.getlist(className, status, profession, (page.getPageNo() - 1) * page.getPageSize(), pageSize);
        for (TSysClass tSysClass : list) {
            tSysClass.setStuNum(studentInfoMapper.selectCount(new LambdaQueryWrapper<TStudentInfo>().eq(TStudentInfo::getClassId,tSysClass.getId())));
        }
        page.setData(list);
        if (page.getPageNo() > page.getTotalPageCount()) {
            page.setPageNo(page.getTotalPageCount());
        }
        return CommonResult.success(page);
    }
    @Resource
    TSysDictDetailServiceImpl dictDetailService;
    @Resource
    SysRoleServiceImpl roleService;
    @Resource
    SysUserServiceImpl userService;
    @Resource
    SysUserRoleServiceImpl userRoleService;
    @ApiOperation("getData => 获取下拉列表数据")
    @GetMapping("/getData")
    @PreAuthorize("@ss.hasPermi('data:class:info')")
    public Object getData(){
        Map<String,Object> map=new HashMap<>();
        //获取专业
        List<TSysDictDetail> zhuanyeList = dictDetailService.list(new LambdaQueryWrapper<TSysDictDetail>()
                .eq(TSysDictDetail::getDictType,"t_data_class_profession"));
        map.put("zhuanyeList",zhuanyeList);
        //获取年级
        List<TSysDictDetail> gradeList = dictDetailService.list(new LambdaQueryWrapper<TSysDictDetail>()
                .eq(TSysDictDetail::getDictType,"qualifications"));
        map.put("gradeList",gradeList);
        //获取所有用户角色信息
        List<SysUserRole> userRoleList = userRoleService.list();
        List<Long> aTeacherUids=new ArrayList<>();
        List<Long> bTeacherUids=new ArrayList<>();
        //班主任
        SysRole aTeacher = roleService.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleKey,"a_teacher"));
        List<SysUser> aTeachers = new ArrayList<>();
        //助理班主任
        SysRole bTeacher = roleService.getOne(new LambdaQueryWrapper<SysRole>().eq(SysRole::getRoleKey,"b_teacher"));
        List<SysUser> bTeachers = new ArrayList<>();
        for (SysUserRole sysUserRole : userRoleList) {
            if (Objects.equals(sysUserRole.getRoleId(), aTeacher.getId())) {
                aTeacherUids.add(sysUserRole.getUserId());
            }
            if (Objects.equals(sysUserRole.getRoleId(), bTeacher.getId())) {
                bTeacherUids.add(sysUserRole.getUserId());
            }
        }
        for (Long aTeacherUid : bTeacherUids) {
            bTeachers.add(userService.getById(aTeacherUid));
        }
        for (Long aTeacherUid : aTeacherUids) {
            aTeachers.add(userService.getById(aTeacherUid));
        }
        map.put("aTeachers",aTeachers);
        map.put("bTeachers",bTeachers);
        //学期
        List<TSysDictDetail> semesterList = dictDetailService.list(new LambdaQueryWrapper<TSysDictDetail>()
                .eq(TSysDictDetail::getDictType,"t_data_class_semester"));
        map.put("semesterList",semesterList);
        return CommonResult.success(map);
    }
    @ApiOperation("addClass => 添加修改班级信息")
    @PostMapping("/addClass")
    @PreAuthorize("@ss.hasPermi('data:class:info')")
    public Object addOrPutClass(@RequestBody TSysClass tSysClass){
        SysUser user = SysUserUtils.getSysUser();
        if (tSysClass.getId() == null) {
            tSysClass.setIsGraduation("0");
            tSysClass.setCreateTime(new Date());
            tSysClass.setCreateBy(user.getUsername());
            tSysClass.setTenantId(user.getId());
            return classService.save(tSysClass)?CommonResult.success():CommonResult.failed("添加失败");
        }else {
            tSysClass.setModifyTime(new Date());
            tSysClass.setModifyBy(user.getUsername());
            return classService.updateById(tSysClass)?CommonResult.success():CommonResult.failed("修改失败");
        }

    }
    @ApiOperation("del => 删除班级信息（软删）")
    @GetMapping("/del/{id}")
    @PreAuthorize("@ss.hasPermi('data:class:info')")
    public Object del(@PathVariable Long id){
        TSysClass tSysClass=new TSysClass();
        tSysClass.setId(id);
        tSysClass.setDel(1);
        return classService.updateById(tSysClass)?CommonResult.success():CommonResult.failed("删除失败");
    }
    @ApiOperation("changeStatus =>更改班级状态")
    @GetMapping("/changeStatus/{id}")
    @PreAuthorize("@ss.hasPermi('data:class:info')")
    public Object changeStatus(@PathVariable Long id){
        TSysClass sysClass = classService.getById(id);
        if (sysClass.getStatus().equals("1")) {
            sysClass.setStatus("2");
        }else {
            sysClass.setStatus("1");
        }
        return classService.updateById(sysClass)?CommonResult.success():CommonResult.failed("更改状态失败");
    }
    @ApiOperation("checkStu =>查看班级学生信息")
    @GetMapping("/checkStu/{id}")
    @PreAuthorize("@ss.hasPermi('data:class:info')")
    public Object checkStu(@PathVariable Long id,
                           @RequestParam Integer pageNo,
                           @RequestParam Integer limit){
        IPage<TStudentInfo> page=studentInfoService.page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNo,limit),
                new LambdaQueryWrapper<TStudentInfo>()
                        .eq(TStudentInfo::getClassId,id));
        return CommonResult.success(page);
    }

}
